#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define BUF_SIZE 30

int main(int argc, char *argv[])
{
    int acpt_sock,recv_sock;
    struct sockaddr_in acpt_addr,recv_addr;
    ssize_t str_len;
    socklen_t recv_addr_size;
    char buf[BUF_SIZE];

    acpt_sock = socket(AF_INET, SOCK_STREAM, 0);
    memset(&acpt_addr, 0, sizeof(acpt_addr));
    acpt_addr.sin_family = AF_INET;
    acpt_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    acpt_addr.sin_port = htons((uint16_t)atoi(argv[1]));

    bind(acpt_sock, (const struct sockaddr *)&acpt_addr, sizeof(acpt_addr));
    listen(acpt_sock, 5);

    recv_addr_size = sizeof(recv_addr);
    recv_sock = accept(acpt_sock, (struct sockaddr *)&recv_addr, &recv_addr_size);

    while(1) {
        str_len = recv(recv_sock, buf, sizeof(buf) - 1, MSG_PEEK | MSG_DONTWAIT);
        if(str_len > 0) {
            break;
        }
    }

    buf[str_len]=0;
    printf("缓冲区 %ld 个字节：%s \n", str_len, buf);

    str_len = recv(recv_sock, buf, sizeof(buf) - 1, 0);
    buf[str_len]=0;
    printf("再次读取：%s\n", buf);

    close(acpt_sock);
    close(recv_sock);
    return 0;
}
